package com.youlu.campus.service.pay.impl;

import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.entity.OrderInfo;
import com.youlu.campus.entity.PayNotifyResultPO;
import com.youlu.campus.service.pay.PayNotifyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class PayNotifyServiceImpl implements PayNotifyService {
    @Autowired
    private MongoTemplate mongoTemplate;

    public void scanPayNotify(Date date) {
        log.info(":>>> 开始扫描订单微信支付通知消息:{}", date);
        Query query = new Query();
        query.addCriteria(Criteria.where("createdTime").gte(new Date(date.getTime() - 60 * 1000)).lte(date));
        List<PayNotifyResultPO> datas = mongoTemplate.find(query, PayNotifyResultPO.class);
        if (Objects.isNull(datas) || CollectionUtils.isEmpty(datas)) {
            log.warn(":>>> 一分钟之内微信通知消息为空");
            return;
        }
        for (PayNotifyResultPO p : datas) {
            if (StringUtils.isBlank(p.getOrderNo()) || Objects.isNull(p)) {
                continue;
            }
            this.syncOrderStatus(p.getOrderNo(), p);
        }

    }

    private void syncOrderStatus(String orderNo, PayNotifyResultPO p) {
        Query query = new Query();
        query.addCriteria(Criteria.where("orderNo").is(orderNo));
        OrderInfo orderInfo = mongoTemplate.findOne(query, OrderInfo.class);
        if (Objects.isNull(orderInfo)) {
            log.error(":>>> 订单不存在:{}", orderNo);
            return;
        }
        if ("0".equals(orderInfo.getStatus()) && "SUCCESS".equals(p.getWxResult().getResult_code()) &&
                StringUtils.isNotBlank(p.getWxResult().getTransaction_id())) {
            log.info(":>>> 订单已经支付成功,收到微信通知:{}", orderNo);
            Update update = new Update();
            update.set("transactionId", p.getWxResult().getTransaction_id());
            update.set("status", "1");
            if (StringUtils.isBlank(orderInfo.getTransactionId())) {
                update.set("transactionId", p.getWxResult().getTransaction_id());
            }
            update.set("updatedTime", new Date());
            UpdateResult result = mongoTemplate.updateFirst(query, update, OrderInfo.class);
            log.info(":>>> 更新订单状态，交易编号，结果为:{},{},{}", orderNo, p.getWxResult().getTransaction_id(), result.getMatchedCount() > 0 ? true : false);
        }

    }

}
